﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace YXShop.Web.membercenter.order
{
    public partial class order_payment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id = ChangeHope.WebPage.PageRequest.GetQueryInt("id");
                this.hlBack.NavigateUrl = "order_info.aspx?OrderId=" + id;
                InitWebControl();
                this.OrderInfoBind(this.GetOrderId(id));
            }
        }
        #region 验证
        private void InitWebControl()
        {
            ChangeHope.WebPage.WebControl.Validate(this.txtPayoutMoney, "输入数字将作为金额", "isint", "必填", "该项必须为数字类型");
            ChangeHope.WebPage.WebControl.Validate(this.txtRemark, "输入相关的备注信息", "isnull", "必填", "该项不能为空");
            ChangeHope.WebPage.WebControl.Validate(this.txtBosomNote, "输入内部信息", "isnull", "必填", "该项不能为空");
            ChangeHope.WebPage.WebControl.SetDate(this.txtAdsumMoneyDate);
            this.txtAdsumMoneyDate.Text = DateTime.Now.ToShortDateString();
            this.Form.Attributes.Add("onsubmit", "return CheckForm()");
        }
        #endregion

        #region 初始化
        /// <summary>
        /// 订单信息初始化
        /// </summary>
        protected void OrderInfoBind(string orderId)
        {
            YXShop.BLL.Order.Orders bll = new YXShop.BLL.Order.Orders();
            YXShop.Model.Order.Orders model = bll.GetModel(orderId);
            if (model != null)
            {
                this.lblUserId.Text = model.UserId;
                this.lblUserName.Text = model.UserId; // 用户名 暂时用 userId
                this.lblOrderId.Text = model.OrderId;
                this.lblMoneyPayed.Text = GetPayed(model.OrderId);//已付款

                this.lblMoneyCount.Text = Convert.ToDouble(model.FactPrice).ToString("f2"); //订单总金额

                this.txtRemark.Text = model.Remark;
                if (Convert.ToDecimal(model.FactPrice) <= Convert.ToDecimal(GetPayed(model.OrderId)))
                {
                    ChangeHope.WebPage.Script.AlertAndGoBack("该订单已经支付清");
                }
                else
                {
                    this.txtPayoutMoney.Text = ((Convert.ToDouble(model.FactPrice.ToString())) - Convert.ToDouble(this.lblMoneyPayed.Text)).ToString();  //需要再支付的金额
                }
            }
        }
        #endregion

        #region 计算商品总价
        private double TotalPrice(string orderId)
        {
            YXShop.BLL.Order.OrderProduct bll = new YXShop.BLL.Order.OrderProduct();
            DataTable dt = bll.GetListOrderProduct(orderId);
            double totalPrice = 0;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    totalPrice += Convert.ToDouble(dt.Rows[i]["ProPrice"].ToString()) * Convert.ToDouble(dt.Rows[i]["ProNum"].ToString());
                }
            }
            return totalPrice;
        }
        #endregion
        #region 公共方法
        /// <summary>
        /// 根据ID得到订单号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        protected string GetOrderId(int id)
        {
            YXShop.BLL.Order.Orders bll = new YXShop.BLL.Order.Orders();
            YXShop.Model.Order.Orders model = bll.GetModel(id);
            if (model != null)
            {
                return model.OrderId;
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 计算已付款
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        protected string GetPayed(string orderId)
        {
            string totle = string.Empty;
            decimal remPrice =0;
            decimal payPrice = 0;
            decimal prePrice = 0;
            //银行支付
            YXShop.BLL.Order.RemittanceInfo remBll = new YXShop.BLL.Order.RemittanceInfo();
            List<YXShop.Model.Order.RemittanceInfo> remdate = remBll.GetAll("orderid='" + orderId + "'");
            if (remdate.Count > 0)
            {
                foreach (YXShop.Model.Order.RemittanceInfo da in remdate)
                {
                    remPrice += Convert.ToDecimal(da.RemittanceMoney.ToString());
                }
            }
            //现金支付
            YXShop.BLL.Order.PaymentMoney payBll = new YXShop.BLL.Order.PaymentMoney();
            List<YXShop.Model.Order.PaymentMoney> paydata = payBll.GetAll("orderid='" + orderId+"'");
            if (paydata.Count > 0)
            {
                foreach (YXShop.Model.Order.PaymentMoney da in paydata)
                {
                    payPrice += Convert.ToDecimal(da.GatheringMoney.ToString());
                }
            }
            //预付款
            YXShop.BLL.Order.PrepayMoney preBll = new YXShop.BLL.Order.PrepayMoney();
            List<YXShop.Model.Order.PrepayMoney> predata = preBll.GetAll("orderid='" + orderId + "'");
            if (predata.Count > 0)
            {
                foreach (YXShop.Model.Order.PrepayMoney da in predata)
                {
                    prePrice += Convert.ToDecimal(da.PayoutMoney);
                }
            }
            totle = (remPrice + payPrice + prePrice).ToString();
            return totle;
        }

        protected int GetUidByUserId(string userId)
        {
            YXShop.BLL.Member.MemberAccount bll = new YXShop.BLL.Member.MemberAccount();
            YXShop.Model.Member.MemberAccount model = bll.GetModel(userId);
            return model.UID;
        }
        #endregion

        protected void lbtnSave_Click(object sender, EventArgs e)
        {
            YXShop.Model.Admin.AdminInfo adminInfo = (YXShop.Model.Admin.AdminInfo)YXShop.Common.AdministrorManager.Get();
            YXShop.BLL.Member.MemberAccount memberBll = new YXShop.BLL.Member.MemberAccount();
            YXShop.Model.Member.MemberAccount memberModel = memberBll.GetModel(this.lblUserId.Text);
            if (Convert.ToDecimal(memberModel.Capital) < Convert.ToDecimal(txtPayoutMoney.Text))
            {
                this.ltlMsg.Text = "操作失败!您的资金少于付款金额，请充值";
                this.pnlMsg.Visible = true;
                this.pnlMsg.CssClass = "actionErr";
                return;
            }
            else
            {

                #region 订单预付款资金
                YXShop.Model.Order.PrepayMoney preModel = new YXShop.Model.Order.PrepayMoney();
                YXShop.BLL.Order.PrepayMoney preBll = new YXShop.BLL.Order.PrepayMoney();
                preModel.OrderId = this.lblOrderId.Text;
                preModel.UserName = this.lblUserId.Text;
                preModel.PayoutMoney = Convert.ToDecimal(this.txtPayoutMoney.Text.Trim());
                preModel.Remark = this.txtRemark.Text;
                preModel.BosomNote = this.txtBosomNote.Text;
                preModel.NoteDate = DateTime.Now;
                preModel.NoteName = adminInfo.AdminName;
                #endregion

                #region 用户交易明细
                YXShop.Model.Member.UserinAndExp userModel = new YXShop.Model.Member.UserinAndExp();
                YXShop.BLL.Member.UserinAndExp userBll = new YXShop.BLL.Member.UserinAndExp();

                //银行资金的明细
                userModel.UID = this.GetUidByUserId(this.lblUserId.Text);
                userModel.AdsumMoneyDate = Convert.ToDateTime(this.txtAdsumMoneyDate.Text);
                userModel.AdsumMoney = Convert.ToDecimal(this.txtPayoutMoney.Text);
                userModel.PresentCoupons = 0;
                userModel.RemitMode = 1;
                userModel.RemitBank = string.Empty;
                userModel.Remark = this.txtRemark.Text;
                userModel.FormMode = string.Empty; //通知方式
                userModel.BosomNote = this.txtBosomNote.Text;
                userModel.NoteDate = DateTime.Now;
                userModel.NoteName = adminInfo.AdminName;
                userModel.InComeandExpState = 1;
                userModel.State = 0;
                userModel.UserId = this.lblUserId.Text;
                #endregion

                #region 订单状态
                YXShop.BLL.Order.Orders orderBll = new YXShop.BLL.Order.Orders();
                YXShop.Model.Order.Orders orderModel = orderBll.GetModel(this.lblOrderId.Text);
                #endregion
                try
                {
                    preBll.Add(preModel);
                    userBll.Add(userModel);

                    #region 操作付款状态 订单状态
                    //已付款+此次汇款的总和
                    decimal payTotail = Convert.ToDecimal(this.GetPayed(this.lblOrderId.Text)) + Convert.ToDecimal(this.txtPayoutMoney.Text.Trim());
                    if (payTotail >= Convert.ToDecimal(TotalPrice(orderModel.Id.ToString())) + Convert.ToDecimal(orderModel.Courier))
                    {
                        orderBll.Amend(orderModel.Id, "OrderStatus", YXShop.Common.OrdersStatusEnum.OrderStatu.未结清.GetHashCode());
                        orderBll.Amend(orderModel.Id, "PaymentStatus", YXShop.Common.OrdersStatusEnum.PaymentStatu.已经付清.GetHashCode());
                        orderBll.Amend(orderModel.Id, "OgisticsStatus", YXShop.Common.OrdersStatusEnum.OgisticsStatus.配送中.GetHashCode());
                    }
                    else
                    {
                        orderBll.Amend(orderModel.Id, "OrderStatus", YXShop.Common.OrdersStatusEnum.OrderStatu.未结清.GetHashCode());
                        orderBll.Amend(orderModel.Id, "PaymentStatus", YXShop.Common.OrdersStatusEnum.PaymentStatu.未付清.GetHashCode());
                    }
                    #endregion

                    #region 如果有多余的钱 就直接转入该用户的账户
                    if (memberModel != null)
                    {
                        decimal Price = decimal.Parse(memberModel.Capital.ToString());
                        if (Convert.ToDecimal(this.txtPayoutMoney.Text) > Price)
                        {
                            ChangeHope.WebPage.BasePage.PageError("用户余额不足！", "order_bank_pay.aspx?OrderId=" + orderModel.Id);
                            return;
                        }
                        memberBll.Amend(memberModel.UID, "Capital", (Convert.ToDecimal(memberModel.Capital.ToString()) - Convert.ToDecimal(this.txtPayoutMoney.Text)));
                    }
                    #endregion

                    this.ltlMsg.Text = "操作成功，已保存该信息";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionOk";
                }
                catch
                {
                    this.ltlMsg.Text = "操作失败!";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                }
                finally
                {
                    adminInfo = null;
                    preModel = null;
                    preBll = null;
                    orderBll = null;
                    orderModel = null;
                    GC.Collect();
                }
            }
        }
    }
}
